/*
 * @Author: xiaosihan
 * @Date: 2024-11-23 22:49:44
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-08-29 20:59:32
 */

import Taro from "@tarojs/taro";
import isEmpty from 'lodash/isEmpty';
import goodsApi from "src/api/goodsApi";
import goodsBaseApi from 'src/api/goodsBaseApi';
import { GoodsData } from 'types/type';
import designerRender from './Designer/designerRender';
import designerStore from './Designer/designerStore';
import perview3der from "./RightTop/PreView2D3D/perview3der";
import textureManager from './textureManager';

// 设置设计器的数据
export default async function setDesignerDate({
    productId,//商品id
    productNegativeId,//底板id
    productDesign,//具体商品设计json
    designName,
    color,//颜色
    colorValue//颜色值
}: {
    productId?: number,//商品id
    productNegativeId: number,//底板id
    productDesign?: GoodsData["productData"],//具体商品设计json
    designName: string,
    color?: string//颜色
    colorValue?: `#${string}`,//颜色值
}) {
    console.log('init editor');
    designerStore.setLoadding(true);
    Taro.showLoading({ title: '加载中' });

    const goodsBaseData = await goodsBaseApi.getProductNegativeById(productNegativeId);
    // 设置底板数据
    designerStore.setGoodsBaseData(goodsBaseData);

    let design_data!: GoodsData['productData'];

    if (productDesign) {
        design_data = productDesign;
    } else {
        const goodsData = await goodsApi.getProductById(productId);
        design_data = goodsData.productData;
    }

    if (color) {
        design_data.color = color;
    }
    if (colorValue) {
        design_data.colorValue = colorValue;
    }
    design_data.designName = designName;

    if (!isEmpty(design_data) && productId) {
        if (["烫画", "直喷"].includes(goodsBaseData.secondaryCraftName)) {
            const currentColor = goodsBaseData.data.colors.find((c) => c.cn === color);
            if (currentColor) {
                designerStore.setDesignColor(currentColor.cn, currentColor.color);
            }
        }
    }

    //删除当前衣服没有的部位 保持设计数据的完整
    for (let c in design_data.designData) {
        if (!goodsBaseData.data.components.map((c) => c.key).includes(c)) {
            delete design_data.designData[c];
        }
    }

    // 保持设计数据的完整
    goodsBaseData.data.components.map((c) => {
        design_data.designData[c.key] = design_data.designData[c.key] || {
            objects: [],
            version: '5.3.0',
            background: "", //局部印的不需要背景 "#e7e2c5"
        };
    });

    // 设置设计数据
    designerStore.setDesignData(design_data);

    //初始化纹理管理器
    console.log(1);
    await textureManager.init(design_data.designData);

    designerRender.requestRenderAll();
    Taro.hideLoading();
    await new Promise(resolve => setTimeout(resolve, 100));
    designerStore.setLoadding(false);

    console.log(2);
    const promises: Array<Promise<any>> = [];

    //初始化上身效果图
    promises.push(perview3der.initMockups(goodsBaseData.data.mini_program_mockup_urls || [], colorValue));

    // 加载颜色对应的上身效果图
    const currentColor = goodsBaseData.data.colors.find((c) => c.color === colorValue);
    if (currentColor) {
        promises.push(
            perview3der.initColorMockups((currentColor.mini_program_mockup_urls || []))
        );
    }

    //加载衣服模型
    if (["升华"].includes(goodsBaseData.secondaryCraftName)) {
        promises.push(
            perview3der.loadCloth(goodsBaseData.data.mini_program_model_url)
        )
    }

    await Promise.all(promises);

    console.log(3);
    //更新衣服模型的贴图
    await perview3der.updataClothMap(goodsBaseData.secondaryCraftName);
    console.log(4);

    //提前加载一下 svg 对应的数据
    await designerRender.get_print_area();

    for (let i = 0; i < 10; i++) {
        await new Promise(resolve => setTimeout(resolve, 1000));
        designerRender.requestRenderAll();
    }

}
